/**
 * 
 */
package com.estock.platform.task;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.estock.common.ESConfig;
import com.estock.common.model.security.Stock;
import com.estock.common.util.CommonUtil;
import com.estock.common.util.DateUtil;
import com.estock.common.util.FileUtil;
import com.estock.platform.http.consts.RequestConsts;
import com.estock.platform.http.request.StockClientRequest;
import com.estock.platform.http.request.StockClientRequest.YahooCsvRequestBuilder;
import com.estock.platform.manager.CacheManager;
import com.estock.platform.task.support.ESJob;

/**
 * @author richard
 *
 */
public class DownloadUrlGenerator extends ESJob {
	
	private static Logger logger = Logger.getLogger(DownloadUrlGenerator.class);
	StringBuilder urls = new StringBuilder();
	
	@Override
	protected void executeJob() {
		String fileName = getYahooCsvManulurlDir() + "manulurls_" + 
				DateUtil.parseString(new Date(), DateUtil.PATTERN_SIMPLE_FORMAT) + ".txt";
		for (Stock stock : getStocksShldUpdateTrans()) {
			YahooCsvRequestBuilder requestBuilder = StockClientRequest
					.getYahooCsvRequestBuilder(RequestConsts.URI_YAHOO_CSV)
					.appendStockCodeAndType(stock.getCode(), stock.getType());
			
			if (stock.getLastTransDay() != null) {
				requestBuilder.appendDateRange(stock.getLastTransDay());
			}
			try {
				StockClientRequest request = (StockClientRequest) requestBuilder.buildQueryMessage();
				urls.append(request.getLocationUri() + "\n");
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			
			FileUtil.writeString(fileName, urls.toString());
			logger.info("Write manulurls to file: " + fileName);
		}
		System.out.println("Write manulurls to file: " + fileName);
		
	}
	
	private String getYahooCsvManulurlDir() {
		return ESConfig.getInstance().getDataFileDir() + "yahoocsv/manulurl/";
	}
	

	protected List<Stock> getStocksShldUpdateTrans() {
		return new ArrayList<Stock>(CacheManager.getInstance().getStocksShldUpdateTrans());
	}
	
	public static void main(String[] args) {
		CommonUtil.isUnitTest = true;
		DownloadUrlGenerator generator = null;
		
//		generator = new DownloadUrlGenerator() {
//			protected List<Stock> getAllStocks() {
//				List<Stock> stocks = new ArrayList<Stock>();
//				stocks.add(new Stock("000625", 2, ""));
//				//stocks.add(new Stock("002024", 2, ""));
// 				return stocks;
//			}
//		};
		generator = new DownloadUrlGenerator();
		generator.executeJob();
	}
}
